// pages/orderConfirm/orderConfirm.js
const addressService = require('../../service/addressService.js')
const orderService = require('../../service/orderService.js')
const shopcart = require('../../service/shopcart.js')
const utils = require('../../utils/util.js');
// load promise 
require('../../utils/wx-pro.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectTabe: 1,//0为快递,1为自提.
    payType: 4,
    rechargeList: [
      {
        key: '余额支付',
        img: 'http://p2sgmzh9e.bkt.clouddn.com/1524131208407.png',
        value: '4'
      },
      {
        key: '微信支付',
        img: 'http://p2sgmzh9e.bkt.clouddn.com/1524131232485.png',
        value: '1'
      }
    ],
    goodInfo: [],
    haveAddress: false,
    deliveryShopInfo: [],
    deliveryAddressInfo: [],
    buyNum: '',
    buyType: '',//1=购物车,2=拼团
    remark: '',//备注
    showToast: false,//显示信息
    toastMsg: '',
    showRemarkBox: false,//显示备注输入框
    mainPrice: '',//小计
    totalPrice: '',//合计
    //new
    goodInfoarr:[],//购物车的商品信息集合
  },

  //错误提示
  showToastFuc(msg) {
    this.setData({
      showToast: true,
      toastMsg: msg
    })
    setTimeout(() => {
      this.setData({
        showToast: false,
        toastMsg: ''
      })
    }, 2000)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    this.getShopInfoByShopId()
    var bt = wx.getStorageSync('buytype')
    this.setData({
      buyType:bt
    })
    this.ValidGoodByCart()
    this.judgeAddress(options)
  },

  judgeAddress() {
    var _this = this
    if (wx.getStorageSync('orderGoods') || wx.getStorageSync('ShopCartList')) {//如果订单商品存在     
      if (_this.data.buyType == 1) {//购物车/单买:设置价格
        var goodarr = JSON.parse(wx.getStorageSync('ShopCartList'))
        _this.setData({
          goodInfoarr: goodarr,
        })
        var godarr = [].concat(this.data.goodInfoarr)
        var countprice=0
        for (var i = 0; i < godarr.length;i++){
          countprice += parseFloat(godarr[i].shoppingCartGoods.goodsPrice * godarr[i].num)
        }
        this.setData({
          mainPrice: (countprice).toFixed(2),
          totalPrice: (countprice).toFixed(2)
        })
      } else {//拼团:设置价格
        var good = JSON.parse(wx.getStorageSync('orderGoods'))//获取订单商品详情
        _this.setData({//获取到的数组good,设置第0个为商品信息
          goodInfo: good[0].goods,
          buyType: good[0].buyType,
          buyNum: good[0].num
        })
        _this.setData({
          mainPrice: _this.data.goodInfo.ptPrice.toFixed(2),
          totalPrice: (_this.data.goodInfo.ptPrice + _this.data.goodInfo.deliveryPrice).toFixed(2)
        })
      }
      if (_this.data.goodInfo.deliverytype == 2) {//如果配送方式为2那么设置为自提
        _this.getShopInfoByShopId()//获取店铺信息
        _this.setData({
          selectTabe: 1
        })
      } else {//快递
        console.log(_this.data.goodInfo.deliverytype)
        _this.setAddress()//
        _this.getShopInfoByShopId()//获取店铺信息
        if (_this.data.goodInfo.deliverytype == 0) {
          if (wx.getStorageSync('IS_EXPRESS') && wx.getStorageSync('IS_EXPRESS') == 'true') {//判断是否是选择了快递配送
            _this.setData({
              selectTabe: 0
            })
          } else {
            _this.setData({
              selectTabe: 1
            })
          }
        } else {
          _this.setData({
            selectTabe: 0
          })
        }
      }
    } else {
      wx.navigateBack({})
    }
  },

  setAddress() {
    var _this = this
    _this.setData({
      haveAddress: false
    })
    if (wx.getStorageSync('selectAddressInfo') && wx.getStorageSync('IS_EXPRESS') == 'true') {//如果配送地址和快递都没问题
      //if (JSON.parse(wx.getStorageSync('selectShopInfo')).id == _this.data.goodInfo.shopId) {//如果storage里的店铺id和商品信息里的店铺id相同
        var selectAddressId = JSON.parse(wx.getStorageSync('selectAddressInfo')).addressId//获取用户选择的地址id
        var params = {
          addressId: selectAddressId
        }
        addressService.getXcxAddress(params).then(data => {
          if (data.code == 200) {
            _this.setData({
              deliveryAddressInfo: data.response.orderAddress
            })
            _this.setData({
              haveAddress: true
            })
          } else {
            this.showToastFuc(data.message)
          }
        })
          .catch(() => {
            console.log('error')
          })
      //}
    }
  },

  ValidGoodByCart() {//通过经纬度来确定商铺然后对商品的库存进行验证
    var _this=this
    var cartids=''
    var goodarr = [].concat(JSON.parse(wx.getStorageSync('ShopCartList')))
    for (var i = 0; i < goodarr.length;i++){
      cartids += goodarr[i].cartId+','
    }
    if (this.data.selectTabe==0){//快递,用户地址坐标
      var useraddress = JSON.parse(wx.getStorageSync('selectAddressInfo'))
      var lat = useraddress.latitude
      var lng = useraddress.longitude
    }else{//自提,自提店铺坐标
      var shopdetail = JSON.parse(wx.getStorageSync('shopdetail'))
      var lat = shopdetail.desLatitude
      var lng = shopdetail.desLongitude
    }
    var param= {
      cartIds: cartids,
      latitude: lat,
      longitude:lng
    }
    shopcart.valid(param).then(r=>{
      console.log("ValidGoodByCart",r)
    })
  },

  getShopInfoByShopId() {//依据shopid获取店铺信息
    var shopid = JSON.parse(wx.getStorageSync('selectShopInfo'))
    var params = {
      shopId: shopid.id
    }
    addressService.getShopById(params).then(data => {
      if (data.code == 200) {
        this.setData({
          deliveryShopInfo: data.response.shop//自提的店铺
        })
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch(() => {
        console.log('error')
      })
  },

  changeType: function (event) {//选项卡的点击事件
    console.log(event.currentTarget.dataset.num)
    // if (this.data.goodInfo.deliverytype == 0) {
      this.setData({
        selectTabe: event.currentTarget.dataset.num
      })
    // } else {
    //   console.log("不支持")
    //   if (event.currentTarget.dataset.num == 0) {
    //     var str = '快递配送'
    //   } else {
    //     var str = '门店自提'
    //   }
    //   this.showToastFuc('该商品暂不支持' + str)
    // }
  },

  radioChange: function (e) {//支付方式
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      payType: e.detail.value
    })
  },

  showMap() {
    var data = this.data.deliveryShopInfo
    var latitude = data.desLatitude
    var longitude = data.desLongitude
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 28,
      name: data.shopName,
      address: data.shopAddress
    })
  },

  callPhone(event) {
    console.log(event.currentTarget.dataset.phone)
    wx.makePhoneCall({
      phoneNumber: event.currentTarget.dataset.phone
    })
  },

  changeAddress() {//更改快递地址
    var shopid = JSON.parse(wx.getStorageSync('selectShopInfo'))
    console.log(shopid)
    wx.navigateTo({
      url: '../orderAddress/orderAddress?shopId=' + shopid.id
    })

  },

  bindTextAreaBlur: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },

  confirmOrder() {
    var _this = this
    if (_this.data.selectTabe == 0) {
      if (!_this.data.deliveryAddressInfo.addressId) {
        _this.showToastFuc("请选择收货地址")
        return false;
      }
      wx.showModal({
        title: '提示',
        content: '您选择的配送方式为【快递】，配送地址为【' + _this.data.deliveryAddressInfo.detailAddress + '】。',
        confirmText: '确认',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {
            _this.goconfirmOrder()
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '您选择的配送方式为【自提】，自提门店为【' + _this.data.deliveryShopInfo.shopName + '】店。',
        confirmText: '确认',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {
            _this.goconfirmOrder()
            wx.setStorageSync('IS_EXPRESS', 'false')
            var info = _this.data.deliveryShopInfo
            var shopInfo = {}
            for (var i in info) {
              if (i == 'shopId') {
                shopInfo.id = info[i]
              } else if (i == 'shopName') {
                shopInfo.name = info[i]
              }
            }
            wx.setStorageSync('selectShopInfo', JSON.stringify(shopInfo))
          }
        }
      })
    }
  },

  goconfirmOrder() {
    var _this = this
    var params = {
      shopId: _this.data.goodInfo.shopId,
      deliveryType: _this.data.selectTabe,
      remark: _this.data.remark,
      expressPrice: 0,
      paymentType: _this.data.payType
    }
    if (_this.data.selectTabe == 0) {
      if (_this.data.deliveryAddressInfo.addressId) {
        params.addressId = _this.data.deliveryAddressInfo.addressId
      }
    }
    if (_this.data.selectTabe == 0 && _this.data.payType == 1) {
      params.expressPrice = _this.data.goodInfo.deliveryPrice
    }
    if (_this.data.buyType == 1) {
      params.goodsId = _this.data.goodInfo.goodsId
      params.num = _this.data.buyNum
      orderService.xcxGoodsOrder(params).then(data => {
        if (data.code == 200) {
          console.log(data.response)
          wx.redirectTo({
            url: '../orderDetail/orderDetail?orderId=' + data.response.order.orderId
          })
        } else {
          _this.showToastFuc(data.message)
        }
      })
        .catch(() => {
          console.log('error')
        })
    } else if (_this.data.buyType == 2) {
      params.XcxGoodsId = _this.data.goodInfo.goodsId
      orderService.xcxOpenGroup(params).then(data => {
        if (data.code == 200) {
          console.log(data.response)
          wx.redirectTo({
            url: '../orderDetail/orderDetail?orderId=' + data.response.xcxOrder.orderId
          })
        } else {
          _this.showToastFuc(data.message)
        }
      })
        .catch(() => {
          console.log('error')
        })
    } else if (_this.data.buyType == 3) {
      params.groupId = JSON.parse(wx.getStorageSync('orderGoods'))[0].groupId
      orderService.JoinXcxOpenGroup(params).then(data => {
        if (data.code == 200) {
          console.log(data.response)
          wx.redirectTo({
            url: '../orderDetail/orderDetail?orderId=' + data.response.xcxOrder.orderId
          })
        } else {
          _this.showToastFuc(data.message)
        }
      })
        .catch(() => {
          console.log('error')
        })
    }
  },
  showRemarkBox() {
    this.setData({
      showRemarkBox: true
    })
  },
  confirmRemark() {
    this.setData({
      showRemarkBox: false
    })
  },
  changeShop() {
    wx.showModal({
      title: '提示',
      content: '是否放弃此订单重新定位？',
      confirmText: '是',
      cancelText: '否',
      success: function (res) {
        if (res.confirm) {
          wx.removeStorageSync('selectShopInfo')
          wx.switchTab({
            url: '../index/index'
          })
        }
      }
    })
  }
})